using System;
using System.Reflection;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using ipi.MCC.Global;

namespace ipi.MCC.Pages
{	
	public delegate void OnTreeChangedHandler(TreeStructureChangedTypes tscEvent, int iNodeID);

    public class MCCTreeAdminControl : System.Web.UI.UserControl
	{
        public ipi.MCC.Controls.MCCTreePath TreePathNavigation;
        protected ipi.MCC.Controls.PeoplePicker ppAddUser;
        protected Button btnAddUser;
        protected Repeater rptUserGroupList;

        protected HiddenField hiddenUseAlphanummericSort;
        protected HtmlInputHidden hiddenNodeID;
		protected Button btnChangeName;
		protected Button btnDeleteNode;
		protected Button btnAddNode;
        protected Button btnUpperNode;
        protected Button btnLowerNode;
        protected Button btnSwitchSorting;
		protected TextBox txtNodeName;		
		protected Label lblDocumentsInArea;
		protected Label lblEditTaxonomy;
		protected Label lblNodeName;
		protected Label lblChangeName;
		protected Label lblCreateNode;
		protected Label lblDeleteNode;
		protected Label lblInfoChangeName;
		protected Label lblInfoCreateNode;
		protected Label lblInfoDeleteNode;
        protected Label lblIsInherited;
        protected Label lblUserSettings;
        protected Label lblAddUser;

		protected CustomValidator validChangeNode;
		protected CustomValidator validGlobal;
				
		public event OnTreeChangedHandler OnTreeChanged;
        public event ipi.MCC.Controls.OnNavigationSelectedHandler OnNavigationSelected;

		protected void Page_Load(object sender, EventArgs e)
		{
			try
			{
                btnAddUser.Click += new EventHandler(btnAddUser_Click);
                rptUserGroupList.ItemCommand += new RepeaterCommandEventHandler(rptUserGroupList_ItemCommand);
                rptUserGroupList.ItemDataBound += new RepeaterItemEventHandler(rptUserGroupList_ItemDataBound);
                TreePathNavigation.OnNavigationSelected += new ipi.MCC.Controls.OnNavigationSelectedHandler(TreePathNavigation_OnNavigationSelected);
                
                if (!Page.IsPostBack)
				{
                    ppAddUser.MultiSelect = false;
                    ppAddUser.AllowEmpty = false;
                    
                    btnAddUser.Text = Resources.Resources.MCCTreeAdminControl_btnAddUser;
                    btnUpperNode.Text = Resources.Resources.MCCTreeAdminControl_btnUpperNode;
                    btnLowerNode.Text = Resources.Resources.MCCTreeAdminControl_btnLowerNode;
                    
                    lblInfoChangeName.Text = Resources.Resources.NavigateHeader_lblInfoChangeName;
					lblInfoCreateNode.Text = Resources.Resources.NavigateHeader_lblInfoCreateNode;
					lblInfoDeleteNode.Text = Resources.Resources.NavigateHeader_lblInfoDeleteNode;

					btnAddNode.Text = Resources.Resources.NavigateHeader_btnAddNode;
					btnChangeName.Text = Resources.Resources.NavigateHeader_btnChangeName;
					btnDeleteNode.Text = Resources.Resources.NavigateHeader_btnDeleteNode;                    
                    btnDeleteNode.Attributes.Add("onclick", "return confirm('" + Resources.Resources.MCCTreeAdminControl_btnDeleteNode_DeleteConfimation + "');");

					lblDocumentsInArea.Text = Resources.Resources.NavigateHeader_lblDocumentsInArea;
					lblEditTaxonomy.Text = Resources.Resources.NavigateHeader_lblEditTaxonomy;
					lblNodeName.Text = Resources.Resources.NavigateHeader_lblNodeName;
					lblChangeName.Text = Resources.Resources.NavigateHeader_lblChangeName;
					lblCreateNode.Text = Resources.Resources.NavigateHeader_lblCreateNode;
					lblDeleteNode.Text = Resources.Resources.NavigateHeader_lblDeleteNode;
                    lblIsInherited.Text = Resources.Resources.NavigateHeader_lblIsInherited;
                    lblUserSettings.Text = Resources.Resources.NavigateHeader_lblUserSettings;
                    lblAddUser.Text = Resources.Resources.NavigateHeader_lblAddUser;

                    //btnAddUser.Enabled = false;
                    btnChangeName.Visible = false;
                    btnDeleteNode.Visible = false;
                    btnUpperNode.Visible = false;
                    btnLowerNode.Visible = false;
					
					if (hiddenNodeID.Value == "")
					{
						hiddenNodeID.Value = "0";
					}

                    SPSite spsCurrent = SPContext.Current.Site;
                    WebSettings wsCurrent = new WebSettings(spsCurrent);
                        
                    using (SPSite spsRoot = new SPSite(!string.IsNullOrEmpty(wsCurrent.MasterWebURL) ? wsCurrent.MasterWebURL : spsCurrent.Url))
                    {
                        WebSettings wsRoot = new WebSettings(spsRoot);
                        SwitchSorting(wsRoot.UseAlphanummericSort);                        
				    }
                }
			}
			catch (Exception exc)
			{
				validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
				validGlobal.IsValid = false;
			}
		}

        protected void SwitchSorting(bool UseAlphanummericSort)
        {
            hiddenUseAlphanummericSort.Value = UseAlphanummericSort.ToString();
            if (UseAlphanummericSort)
            {
                btnSwitchSorting.Text = Resources.Resources.NavigateHeader_btnSwitchSorting_Manually;
                btnSwitchSorting.Style[HtmlTextWriterStyle.BackgroundImage] = "url('../../_layouts/images/MCC/RemoveFilter.gif')";
            }
            else
            {
                btnSwitchSorting.Text = Resources.Resources.NavigateHeader_btnSwitchSorting_Alpha;
                btnSwitchSorting.Style[HtmlTextWriterStyle.BackgroundImage] = "url('../../_layouts/images/MCC/SortA-z.gif')";
                btnLowerNode.Visible = false;
                btnUpperNode.Visible = false;
            }
        }
        
        protected void TreePathNavigation_OnNavigationSelected(int iNodeID)
        {
            if (OnNavigationSelected != null)
            {
                OnNavigationSelected(iNodeID);
            }
        }

        public void SelectNode(SPList splNodes, TreeNode NodePath)
        {
            int NodeID = Convert.ToInt32(NodePath.Value);
            hiddenNodeID.Value = NodeID.ToString();

            if (NodeID > 0)
            {
                btnAddUser.Enabled = true;
                btnChangeName.Visible = true;
                btnDeleteNode.Visible = true;

                if (Convert.ToBoolean(hiddenUseAlphanummericSort.Value))
                {
                    btnUpperNode.Visible = false;
                    btnLowerNode.Visible = false;
                }
                else
                {
                    btnUpperNode.Visible = true;
                    btnLowerNode.Visible = true;                
                }

                TreeNode tnParent = NodePath.Parent;
                int iNodeIndex = tnParent.ChildNodes.IndexOf(NodePath);
                if (iNodeIndex == tnParent.ChildNodes.Count - 1)
                {
                    btnLowerNode.Visible = false;
                }

                if (iNodeIndex == 0)
                {
                    btnUpperNode.Visible = false;
                }
            }
            else
            {
                btnAddUser.Enabled = false;
                btnChangeName.Visible = false;
                btnDeleteNode.Visible = false;
                btnLowerNode.Visible = false;
                btnUpperNode.Visible = false;
            }
            
            TreePathNavigation.SetTreePath(NodePath);
            SetUserRightsList(splNodes, NodeID);
        }
        
        private void SetUserRightsList(SPList splNodes, int iNodeID)
        {
            try
            {
                DataTable dtUserRights = new DataTable("UserRights");
                DataColumn dcName = new DataColumn("UserGroupName", System.Type.GetType("System.String"));
                DataColumn dcID = new DataColumn("ID", System.Type.GetType("System.Int32"));
                dtUserRights.Columns.Add(dcName);
                dtUserRights.Columns.Add(dcID);
                
                if (iNodeID > 0)
                {
                    SPListItem splCurrentNode = ipi.MCC.Global.Functions.GetSingleTreeNode(splNodes, iNodeID);

                    lblIsInherited.Visible = !splCurrentNode.HasUniqueRoleAssignments;
                    
                    foreach (SPRoleAssignment raCurrent in splCurrentNode.RoleAssignments)
                    {
                        bool bHasReadRights = false;
                        foreach(SPRoleDefinition rdCurrent in raCurrent.RoleDefinitionBindings)
                        {
                            if ((rdCurrent.BasePermissions.ToString().Contains("ViewListItem")) || (rdCurrent.BasePermissions == SPBasePermissions.FullMask))
                            {
                                bHasReadRights = true;
                            }
                        }

                        if (bHasReadRights)
                        {
                            DataRow drNew = dtUserRights.NewRow();

                            drNew[dcName] = raCurrent.Member.Name;
                            drNew[dcID] = raCurrent.Member.ID;

                            dtUserRights.Rows.Add(drNew);
                        }
                    }
                }

                rptUserGroupList.DataSource = dtUserRights;
                rptUserGroupList.DataBind();
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
        }

        protected void rptUserGroupList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                LinkButton lnkRemoveUserGroup = (LinkButton)e.Item.FindControl("lnkRemoveUserGroup");

                if (lnkRemoveUserGroup != null)
                {
                    lnkRemoveUserGroup.Text = Resources.Resources.MCCTreeAdminControl_lnkRemoveUserGroup;
                }
            }
        }

        protected void rptUserGroupList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                SPSite spsCurrent = SPContext.Current.Site;
                WebSettings wsCurrent = new WebSettings(spsCurrent);

                using (SPSite spsRoot = new SPSite(!string.IsNullOrEmpty(wsCurrent.MasterWebURL) ? wsCurrent.MasterWebURL : spsCurrent.Url))
                {
                    SPWeb spwRoot = spsRoot.RootWeb;

                    SPList splNodes = Functions.GetTreeList(spwRoot);

                    SPListItem splCurrentNode = ipi.MCC.Global.Functions.GetSingleTreeNode(splNodes, Convert.ToInt32(hiddenNodeID.Value));

                    if (!splCurrentNode.HasUniqueRoleAssignments)
                    {
                        splCurrentNode.BreakRoleInheritance(true);
                    }

                    splCurrentNode.RoleAssignments.RemoveById(Convert.ToInt32(e.CommandArgument));

                    SetUserRightsList(splNodes, Convert.ToInt32(hiddenNodeID.Value)); 
                }
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
        }
        
        protected void btnUpperNode_Click(object sender, EventArgs e)
        {
            ChangeNodeOrder("<", "desc", TreeStructureChangedTypes.UpperNode);
        }

        protected void btnLowerNode_Click(object sender, EventArgs e)
        {
            ChangeNodeOrder(">", "asc", TreeStructureChangedTypes.LowerNode);
        }

        protected void btnSwitchSorting_Click(object sender, EventArgs e)
        {
            SPSite spsCurrent = SPContext.Current.Site;
            WebSettings wsCurrent = new WebSettings(spsCurrent);

            using (SPSite spsRoot = new SPSite(!string.IsNullOrEmpty(wsCurrent.MasterWebURL) ? wsCurrent.MasterWebURL : spsCurrent.Url))
            {
                WebSettings wsRoot = new WebSettings(spsRoot);
                wsRoot.UseAlphanummericSort = !wsRoot.UseAlphanummericSort;
                wsRoot.Update();

                SwitchSorting(wsRoot.UseAlphanummericSort);

                if (OnTreeChanged != null)
                {
                    OnTreeChanged(TreeStructureChangedTypes.SwitchSorting, int.MinValue);
                }
            }
        }
        
        private void ChangeNodeOrder(string sOperator, string sOrder, TreeStructureChangedTypes sctEvent)
        {
            try
            {
                SPSite spsCurrent = SPContext.Current.Site;
                WebSettings wsCurrent = new WebSettings(spsCurrent);

                using (SPSite spsRoot = new SPSite(!string.IsNullOrEmpty(wsCurrent.MasterWebURL) ? wsCurrent.MasterWebURL : spsCurrent.Url))
                {
                    SPWeb spwRoot = spsRoot.RootWeb;
                    SPList splNodes = Functions.GetTreeList(spwRoot);
                    SPListItem sliCurrent = Functions.GetSingleTreeNode(splNodes, Convert.ToInt32(hiddenNodeID.Value));
                    if (sliCurrent != null)
                    {
                        int iParentNode = new SPFieldLookupValue((string)sliCurrent["ParentNode"]).LookupId;
                        int iNodeOrder = Convert.ToInt32(sliCurrent["NodeOrder"]);

                        SPListItemCollection licCurrentLevel = ipi.MCC.Global.Functions.GetTreeChildNode(splNodes, iParentNode == 0 ? -1 : iParentNode);
                        if (licCurrentLevel != null)
                        {
                            DataTable dtCurrentLevel = licCurrentLevel.GetDataTable();
                            DataView dvCurrentLevel = new DataView(dtCurrentLevel,
                                                                   "NodeOrder " + sOperator + " " + iNodeOrder.ToString(),
                                                                   "NodeOrder " + sOrder, DataViewRowState.CurrentRows);

                            if (dvCurrentLevel.Count > 0)
                            {
                                DataRowView drvNextNode = dvCurrentLevel[0];
                                int iNextNodeOrder = Convert.ToInt32(drvNextNode["NodeOrder"]);
                                SPListItem sliNextNode = ipi.MCC.Global.Functions.GetSingleTreeNode(splNodes, Convert.ToInt32(drvNextNode["ID"]));

                                if (sliNextNode != null)
                                {
                                    sliNextNode["NodeOrder"] = iNodeOrder;
                                    sliCurrent["NodeOrder"] = iNextNodeOrder;

                                    sliNextNode.Update();
                                    sliCurrent.Update();

                                    if (OnTreeChanged != null)
                                    {
                                        OnTreeChanged(sctEvent, Convert.ToInt32(hiddenNodeID.Value));
                                    }
                                }
                            }
                            else
                            {
                                if (sctEvent == TreeStructureChangedTypes.UpperNode)
                                {
                                    iNodeOrder--;
                                }
                                else
                                {
                                    iNodeOrder++;
                                }

                                sliCurrent["NodeOrder"] = iNodeOrder;
                                sliCurrent.Update();

                                if (OnTreeChanged != null)
                                {
                                    OnTreeChanged(sctEvent, Convert.ToInt32(hiddenNodeID.Value));
                                }
                            }
                        }
                    } 
                }
            }
            catch (Exception exc)
            {
                validChangeNode.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validChangeNode.IsValid = false;
            }
        }
        
        protected void btnAddNode_Click(object sender, EventArgs e)
		{
			if (txtNodeName.Text == "")
			{
                validChangeNode.ErrorMessage = Exceptions.HandleException(new UserHandlingException(Resources.Resources.NavigateHeader_NodeNameRequired), this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
				validChangeNode.IsValid = false;
			}
			else
			{
				try
				{
                    SPSite spsCurrent = SPContext.Current.Site;
                    WebSettings wsCurrent = new WebSettings(spsCurrent);

                    using (SPSite spsRoot = new SPSite(!string.IsNullOrEmpty(wsCurrent.MasterWebURL) ? wsCurrent.MasterWebURL : spsCurrent.Url))
                    {
                        SPWeb spwRoot = spsRoot.RootWeb;
                        SPList splTree = Functions.GetTreeList(spwRoot);
                        SPListItem liNew = splTree.Items.Add();
                        liNew["Title"] = txtNodeName.Text;
                        liNew["ParentNode"] = hiddenNodeID.Value;
                        liNew["NodeOrder"] = GetNextNodeOrder(splTree, Convert.ToInt32(hiddenNodeID.Value)).ToString();
                        liNew.Update();

                        hiddenNodeID.Value = liNew["ows_ID"].ToString();
                        txtNodeName.Text = "";

                        if (OnTreeChanged != null)
                        {
                            OnTreeChanged(TreeStructureChangedTypes.AddedNode, Convert.ToInt32(hiddenNodeID.Value));
                        } 
                    }
				}
				catch (Exception exc)
				{
                    validChangeNode.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                    validChangeNode.IsValid = false;
				}
			}
		}

        private int GetNextNodeOrder(SPList splTreeList, int iNodeID)
        {
            int iNextNodeOrder = 0;

            try
            {
                SPListItemCollection licCurrentNode = ipi.MCC.Global.Functions.GetTreeChildNode(splTreeList, iNodeID == 0 ? -1 : iNodeID);
                if ((licCurrentNode != null) && (licCurrentNode.Count > 0))
                {
                    DataTable dtOrder = licCurrentNode.GetDataTable();
                    DataView dvOrder = new DataView(dtOrder, "", "NodeOrder desc", DataViewRowState.CurrentRows);
                    DataRowView drvTop = dvOrder[0];
                    if (drvTop["NodeOrder"] != DBNull.Value)
                    {
                        iNextNodeOrder = Convert.ToInt32(drvTop["NodeOrder"]) + 1;
                    }
                }
            }
            catch (Exception exc)
            {
                validChangeNode.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validChangeNode.IsValid = false;
            }

            return iNextNodeOrder;
        }

        protected void btnChangeName_Click(object sender, EventArgs e)
		{
			if (txtNodeName.Text == "")
			{
                validChangeNode.ErrorMessage = Exceptions.HandleException(new UserHandlingException(Resources.Resources.NavigateHeader_NodeSelected), this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
				validChangeNode.IsValid = false;
			}
			else
			{
				try
				{
                    SPSite spsCurrent = SPContext.Current.Site;
                    WebSettings wsCurrent = new WebSettings(spsCurrent);

                    using (SPSite spsRoot = new SPSite(!string.IsNullOrEmpty(wsCurrent.MasterWebURL) ? wsCurrent.MasterWebURL : spsCurrent.Url))
                    {
                        SPWeb spwRoot = spsRoot.RootWeb;
                        SPList splNodes = Functions.GetTreeList(spwRoot);
                        SPListItem liChangeNode = ipi.MCC.Global.Functions.GetSingleTreeNode(splNodes, Convert.ToInt32(hiddenNodeID.Value));
                        if (liChangeNode != null)
                        {
                            liChangeNode["Title"] = txtNodeName.Text;
                            liChangeNode.Update();

                            txtNodeName.Text = "";

                            if (OnTreeChanged != null)
                            {
                                OnTreeChanged(TreeStructureChangedTypes.RenamedNode, Convert.ToInt32(hiddenNodeID.Value));
                            }
                        }
                        else
                        {
                            validChangeNode.ErrorMessage = Exceptions.HandleException(new UserHandlingException(Resources.Resources.NavigateHeader_NodeNotFound), this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                            validChangeNode.IsValid = false;
                        } 
                    }
				}
				catch (Exception exc)
				{
                    validChangeNode.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
					validChangeNode.IsValid = false;
				}
			}
		}

		protected void btnDeleteNode_Click(object sender, EventArgs e)
		{
			bool bIsEmpty = true;
			int iCurrentNodeID = Convert.ToInt32(hiddenNodeID.Value);

            SPSite spsCurrent = SPContext.Current.Site;
            WebSettings wsCurrent = new WebSettings(spsCurrent);

            using (SPSite spsRoot = new SPSite(!string.IsNullOrEmpty(wsCurrent.MasterWebURL) ? wsCurrent.MasterWebURL : spsCurrent.Url))
            {
                SPWeb spwRoot = spsRoot.RootWeb;
                SPList splTree = Functions.GetTreeList(spwRoot);
                try
                {
                    IsTreeEmpty(splTree, iCurrentNodeID, ref bIsEmpty, wsCurrent);

                    if (bIsEmpty)
                    {
                        DeleteTreeNode(splTree, iCurrentNodeID, wsCurrent);

                        if (OnTreeChanged != null)
                        {
                            OnTreeChanged(TreeStructureChangedTypes.DeletedNode, iCurrentNodeID);
                        }
                    }
                    else
                    {
                        validChangeNode.ErrorMessage = Exceptions.HandleException(new UserHandlingException(Resources.Resources.NavigateHeader_NodeNotEmpty), this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                        validChangeNode.IsValid = false;
                    }
                }
                catch (Exception exc)
                {
                    validChangeNode.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                    validChangeNode.IsValid = false;
                } 
            }
		}

        private void IsTreeEmpty(SPList splTree, int iNodeID, ref bool bIsEmpty, WebSettings wsCurrent)
        {
            if (bIsEmpty)
            {

                if (MCCData.GetCurrentDocumentCount(iNodeID) > 0)
                {
                    bIsEmpty = false;
                }
                else
                {
                    SPListItemCollection licNodeChildes = ipi.MCC.Global.Functions.GetTreeChildNode(splTree, iNodeID);
                    foreach (SPListItem sliCurrentChild in licNodeChildes)
                    {
                        int iChildNodeID = Convert.ToInt32(sliCurrentChild["ows_ID"]);
                        IsTreeEmpty(splTree, iChildNodeID, ref bIsEmpty, wsCurrent);
                    }
                }
            }
        }

        private void DeleteTreeNode(SPList splTreeNode, int iNodeID, WebSettings wsCurrent)
        {
            DeleteTreeSubNode(splTreeNode, iNodeID, wsCurrent);
            SPListItem liCurrentNode = ipi.MCC.Global.Functions.GetSingleTreeNode(splTreeNode, iNodeID);
            liCurrentNode.Delete();
        }

        private void DeleteTreeSubNode(SPList splTreeNode, int iNodeID, WebSettings wsCurrent)
        {
            SPListItemCollection licNodeChildes = ipi.MCC.Global.Functions.GetTreeChildNode(splTreeNode, iNodeID);

            while (licNodeChildes.Count > 0)
            {
                SPListItem sliCurrentChild = licNodeChildes[0];
                int iChildNodeID = Convert.ToInt32(sliCurrentChild["ows_ID"]);
                DeleteTreeSubNode(splTreeNode, iChildNodeID, wsCurrent);
                sliCurrentChild.Delete();
            }
        }

        protected void btnAddUser_Click(object sender, EventArgs e)
        {
            try
            {
                if (ppAddUser.IsValid)
                {

                    SPSite spsCurrent = SPContext.Current.Site;
                    WebSettings wsCurrent = new WebSettings(spsCurrent);

                    using (SPSite spsRoot = new SPSite(!string.IsNullOrEmpty(wsCurrent.MasterWebURL) ? wsCurrent.MasterWebURL : spsCurrent.Url))
                    {
                        SPWeb spwRoot = spsRoot.RootWeb;
                        SPList splNodes = Functions.GetTreeList(spwRoot);

                        SPListItem liCurrentNode = ipi.MCC.Global.Functions.GetSingleTreeNode(splNodes, Convert.ToInt32(hiddenNodeID.Value));

                        if (!liCurrentNode.HasUniqueRoleAssignments)
                        {
                            liCurrentNode.BreakRoleInheritance(true);
                        }

                        SPRoleAssignmentCollection racCurrent = liCurrentNode.RoleAssignments;

                        SPRoleDefinition rdReader = null;
                        foreach (SPRoleDefinition rdCurrent in SPContext.Current.Web.RoleDefinitions)
                        {
                            switch (rdCurrent.Type)
                            {
                                case SPRoleType.Reader:
                                    rdReader = rdCurrent;
                                    break;
                            }
                        }

                        SPPrincipal sppSelected = this.ppAddUser.GetUserData();

                        SPRoleAssignment raReader = new SPRoleAssignment(sppSelected);
                        raReader.RoleDefinitionBindings.Add(rdReader);
                        racCurrent.Add(raReader);

                        SetUserRightsList(splNodes, Convert.ToInt32(hiddenNodeID.Value)); 
                    }
                }

            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
        }
	}
}